/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.seckill.platform.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.OfflineHandleEventType;
import com.yami.shop.bean.model.OfflineHandleEvent;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.param.OfflineHandleEventAuditParam;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.seckill.comment.model.Seckill;
import com.yami.shop.seckill.comment.service.SeckillService;
import com.yami.shop.seckill.comment.service.SeckillSkuService;
import com.yami.shop.seckill.platform.dto.SeckillProdDto;
import com.yami.shop.security.platform.util.SecurityUtils;
import com.yami.shop.service.OfflineHandleEventService;
import com.yami.shop.service.ProductService;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 秒杀信息
 *
 * @author LGH
 * @date 2019-08-28 09:36:59
 */
@RestController
@AllArgsConstructor
@RequestMapping("/platform/seckill")
public class SeckillController {

    private final SeckillService seckillService;

    private final MapperFacade mapperFacade;

    private final ProductService productService;

    private final SeckillSkuService seckillSkuService;

    private final OfflineHandleEventService offlineHandleEventService;

    /**
     * 分页查询
     *
     * @param page    分页对象
     * @param seckill 秒杀信息1
     * @return 分页数据
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<Seckill>> getSeckillPage(PageParam<Seckill> page, Seckill seckill) {
        IPage<Seckill> seckillPage = seckillService.getPlatformSeckillPage(page, seckill);
        return ResponseEntity.ok(seckillPage);
    }

    /**
     * 通过id查询秒杀信息
     *
     * @param seckillId id
     * @return 单个数据
     */
    @GetMapping("/info/{seckillId}")
    public ResponseEntity<SeckillProdDto> getById(@PathVariable("seckillId") Long seckillId) {
        Seckill seckill = seckillService.getSeckillById(seckillId);

        SeckillProdDto dto = new SeckillProdDto();
        dto.setSeckill(seckill);
        dto.setSeckillSkus(seckillSkuService.listSeckillSkuBySeckillId(seckillId));
        Product product = productService.getProductByProdId(seckill.getProdId(), I18nMessage.getDbLang());
        dto.setProd(product);
        return ResponseEntity.ok(dto);
    }

    /**
     * 通过id使秒杀商品失效
     *
     * @param seckillId id
     * @return 是否删除成功
     */
    @SysLog("使秒杀失效信息")
    @PutMapping("/invalid/{seckillId}")
    public ResponseEntity<Void> invalidById(@PathVariable Long seckillId) {
        Seckill seckill = seckillService.getSeckillById(seckillId);
        seckillService.invalidById(seckill);

        productService.removeProdCacheByProdId(seckill.getProdId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
        productService.removeProdCacheByProdId(seckill.getProdId(),LanguageEnum.LANGUAGE_EN.getLang());
        seckillSkuService.removeSeckillSkuCacheBySeckillId(seckill.getSeckillId());
        seckillService.removeSeckillCacheById(seckill.getSeckillId());
        return ResponseEntity.ok().build();
    }

    /**
     * 通过id删除秒杀信息
     *
     * @param seckillId id
     * @return 是否删除成功
     */
    @SysLog("删除秒杀信息")
    @DeleteMapping("/{seckillId}")
    public ResponseEntity<Void> removeById(@PathVariable Long seckillId) {
        Seckill seckill = seckillService.getSeckillById(seckillId);
        if (!Objects.equals(0, seckill.getStatus())) {
            // 秒杀活动未关闭，无法删除
            throw new YamiShopBindException("yami.seckill.cannot.delete");
        }
        seckill.setIsDelete(1);
        seckillService.updateById(seckill);
        seckillSkuService.removeSeckillSkuCacheBySeckillId(seckill.getSeckillId());
        return ResponseEntity.ok().build();
    }

    /**
     * 通过活动id获取下线信息
     */
    @GetMapping("/getOfflineHandleEventBySeckillId/{seckillId}")
    @PreAuthorize("@pms.hasPermission('platform:seckill:info')")
    public ResponseEntity<OfflineHandleEvent> getOfflineHandleEventByDiscountId(@PathVariable("seckillId") Long seckillId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.SECKILL.getValue(), seckillId);
        return ResponseEntity.ok(offlineHandleEvent);
    }

    /**
     * 下线活动
     */
    @PostMapping("/offline")
    @PreAuthorize("@pms.hasPermission('platform:seckill:update')")
    public ResponseEntity<Void> offline(@RequestBody OfflineHandleEvent offlineHandleEvent) {
        Seckill seckill = seckillService.getSeckillById(offlineHandleEvent.getHandleId());
        if (seckill == null) {
            // 未找到该秒杀活动信息
            throw new YamiShopBindException("yami.activity.cannot.find");
        }
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        seckillService.offline(seckill, offlineHandleEvent.getOfflineReason(), sysUserId);

        // 移除缓存
        seckillService.removeSeckillCacheById(seckill.getSeckillId());
        return ResponseEntity.ok().build();
    }

    /**
     * 审核活动
     */
    @PostMapping("/auditSeckill")
    @PreAuthorize("@pms.hasPermission('platform:seckill:update')")
    public ResponseEntity<Void> auditSeckill(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        Seckill seckill = seckillService.getSeckillById(offlineHandleEventAuditParam.getHandleId());
        if (seckill == null) {
            // 未找到该秒杀活动信息
            throw new YamiShopBindException("yami.activity.cannot.find");
        }
        seckillService.auditSeckill(offlineHandleEventAuditParam, sysUserId);

        // 移除缓存
        seckillService.removeSeckillCacheById(seckill.getSeckillId());
        return ResponseEntity.ok().build();
    }


}
